package com.basker.pisces.auth.domain.entity.command;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.util.CollectionUtils;

import com.basker.pisces.auth.domain.entity.AuthUserEntity;
import com.basker.pisces.auth.domain.exception.AuthUserRegisteredException;
import com.basker.pisces.domain.ISupportEntityLimit;
import com.basker.pisces.domain.command.exception.CommandExecuteInvalidObjectException;
import com.basker.pisces.domain.command.meta.SaveCommand;
import com.basker.pisces.domain.constant.DomainConstants.ObjectErrorCode;
import com.basker.pisces.domain.entity.meta.Entity;
import com.basker.pisces.domain.validation.ValidationErrors;
import com.basker.pisces.domain.validation.ValidationErrorsUtils;
import com.basker.pisces.domain.validation.meta.UniquePropertyValidation;
import com.basker.pisces.service.exception.IObjectErrorsWrapper.ObjectError;

public class AuthUserRegistCommand extends SaveCommand implements ISupportEntityLimit {

    public AuthUserRegistCommand() {
        this.setName(AuthUserRegistCommand.class.getSimpleName());
    }

    @Override
    public Class<? extends Entity> getLimitEntiyType() {
        return AuthUserEntity.class;
    }

    @Override
    public String getRunnerBeanName() {
        return "saveCommandRunner";
    }

    @Override
    public CommandExecuteInvalidObjectException wrapperValidationErrors(ValidationErrors errors) {
        List<ObjectError> objectErrors = ValidationErrorsUtils.findErrorsByValidation(errors.getValidationErrors(),
                UniquePropertyValidation.class);
        if (!CollectionUtils.isEmpty(objectErrors)) {
            // 唯一性校验有两种类型的错误，1个是并发提交冲突，另一个是数据库已存在，后者才需要转义成AuthUserRegisteredException
            objectErrors = objectErrors.stream().filter(e -> e.getErrorCode() == ObjectErrorCode.UNIQUE_EXIST_VIOLATION)
                    .collect(Collectors.toList());
        }

        if (CollectionUtils.isEmpty(objectErrors)) {
            return null;
        }

        return new AuthUserRegisteredException(objectErrors);
    }

}
